//
//  AppNotificationManager.m
//  Water
//
//  Created by yh on 2017/11/27.
//  Copyright © 2017年 chenguibang. All rights reserved.
//

#import "AppNotificationManager.h"
#import <UserNotifications/UserNotifications.h>
#import "AppClient.h"
#import <AudioToolbox/AudioToolbox.h>

@implementation AppNotificationManager
+ (instancetype)shareManager{
    static dispatch_once_t onceToken;
    static AppNotificationManager *shareInstance = nil;
    dispatch_once(&onceToken, ^{
        shareInstance = [[AppNotificationManager alloc]init];
    });
    return shareInstance;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
     
    }
    return self;
}

//定时推送
- (void)createLocalizedUserNotification{

    
}

- (void)refresh{
    // 申请通知权限
    [[UNUserNotificationCenter currentNotificationCenter] requestAuthorizationWithOptions:(UNAuthorizationOptionAlert | UNAuthorizationOptionSound | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
            UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
            [center removeAllDeliveredNotifications];
            [center removeAllPendingNotificationRequests];
            for (PlanItem *plan in [AppClient shared].plans) {
                UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:plan.notification.dateComponents repeats:YES];
                // 创建通知内容 UNMutableNotificationContent, 注意不是 UNNotificationContent ,此对象为不可变对象。
                UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
                content.title = plan.notification.title;
                content.subtitle = plan.notification.subtitle;
                content.body = plan.notification.body;
                content.sound = plan.notification.ring ? [UNNotificationSound soundNamed:plan.notification.ring] : [UNNotificationSound defaultSound];
                content.badge = @(0);
                //        content.userInfo = @{@"key1":@"value1",@"key2":@"value2"};
                NSString *requestIdentifier = plan.notification.identifier;
                UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:requestIdentifier content:content trigger:trigger];
                UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
                [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
                    if (!error) {
                        
                    }
                }];
            }
        }
    }];
}

@end
